﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Linq;
using ModuleBase;
using ModuleBase.googoltech.GTS;
using Prism.Ioc;

namespace AxisMoveModel
{
    public class AxisMoveModule : ModuleBase.ModuleBase
    {
        private IContainerProvider _containerProvider;
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;
        bool outputs = false;
        int _count = 0;
        private int _parameter1 = 1;
        public int Parameter1
        {
            get => _parameter1;
            set
            {
                if (_parameter1 != value)
                {
                    _parameter1 = value;
                    OnPropertyChanged(nameof(Parameter1));
                }
            }
        }

        private double _parameter2;
        public double Parameter2
        {
            get => _parameter2;
            set
            {
                if (_parameter2 != value)
                {
                    _parameter2 = value;
                    OnPropertyChanged(nameof(Parameter2));
                }
            }
        }

        private string _parameter3 = "正向";
        public string Parameter3
        {
            get => _parameter3;
            set
            {
                if (_parameter3 != value)
                {
                    _parameter3 = value;
                    OnPropertyChanged(nameof(Parameter3));
                }
            }
        }

        private double _parameter4;
        public double Parameter4
        {
            get => _parameter4;
            set
            {
                if (_parameter4 != value)
                {
                    _parameter4 = value;
                    OnPropertyChanged(nameof(Parameter4));
                }
            }
        }
        private string _parameter5 = "Top_A8";
        public string Parameter5
        {
            get => _parameter5;
            set
            {
                if (_parameter5 != value)
                {
                    _parameter5 = value;
                    OnPropertyChanged(nameof(Parameter5));
                }
            }
        }
        public override Dictionary<string, object> GetProperties()
        {
            return new Dictionary<string, object>
            {
                { "轴号", Parameter1 },
                { "速度", Parameter2 },
                { "方向", Parameter3 },
                { "距离", Parameter4 },
                { "轴卡参数名", Parameter5 },
            };
        }

        public override Dictionary<string, List<object>> PropertyOptions { get; } = new Dictionary<string, List<object>>
        {
            { "方向", new List<object> { "正向", "负向" } },
            { "轴号", new List<object>{ 1,2,3,4,5,6,7,8 } }
        };

        public AxisMoveModule(IContainerProvider containerProvider, ModuleStateService moduleStateService)
        {
            _containerProvider = containerProvider;
            _moduleStateService = moduleStateService;
            _moduleStateService.RegisterModule(Id);
            Name = "轴Jog";

            DisplayNameToPropertyNameMap = new Dictionary<string, string>
            {
                { "轴号", nameof(Parameter1) },
                { "速度", nameof(Parameter2) },
                { "方向", nameof(Parameter3) },
                { "距离", nameof(Parameter4) },
                { "轴卡参数名", nameof(Parameter5) }
            };
        }

        public override bool Execute()
        {
            AxisParm _axis;
            _axisCardService = _containerProvider.Resolve<IAxisCardService>(Parameter5);
            Status = ModuleBase.ModuleStatus.Executing; // 设置状态为执行中
            try
            {
                switch ((int)Parameter1)
                {
                    case 1:
                        _axis = _axisCardService.A1;
                        break;
                    case 2:
                        _axis = _axisCardService.A2;
                        break;
                    case 3:
                        _axis = _axisCardService.A3;
                        break;
                    case 4:
                        _axis = _axisCardService.A4;
                        break;
                    case 5:
                        _axis = _axisCardService.A5;
                        break;
                    case 6:
                        _axis = _axisCardService.A6;
                        break;
                    case 7:
                        _axis = _axisCardService.A7;
                        break;
                    case 8:
                        _axis = _axisCardService.A8;
                        break;
                    default:
                        _axis = _axisCardService.A1;
                        break;
                }
                var curPos = GTSCard.GetPos(_axis);
                double _tarPos = 0;
                if (Parameter3 == "正向")
                {
                    _tarPos = curPos + Parameter4;
                }
                else
                {
                    _tarPos = curPos - Parameter4;
                }
                CancellationTokenSource source1 = new CancellationTokenSource();
                CancellationToken token = source1.Token;
                GoAction(token, _axis, _tarPos, Parameter2);
                Thread.Sleep(1000);
                outputs = true;
            }
            catch (Exception exp)
            {
                MyFunc.AddMessage($"模块[{Name}]执行异常,参数轴号{Parameter1}，速度{Parameter2}，方向{Parameter3}，距离{Parameter4}：" + exp.ToString());
                outputs = false;
            }
            return outputs;
        }

        public override async Task<bool> ExecuteAsync()
        {
            var result = await Task.Run(() => Execute());
            return result;
        }

        public override void Initialize()
        {

        }

        private void GoAction(CancellationToken token, AxisParm axisN, double tartgetN, double speed)
        {
            try
            {
                int stepnum = 0;
                Stopwatch sw = Stopwatch.StartNew();
                while (true)
                {
                    if (token.IsCancellationRequested && _moduleStateService.IsStopped)
                    {
                        GTSCard.AxisStop(axisN, 0);
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0:
                            {
                                GTSCard.AxisPosMove(ref axisN, tartgetN, speed);
                                MyFunc.AddMessage($"轴{axisN.AxisId}开始移动");
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisN))
                            {
                                MyFunc.AddMessage($"轴{axisN.AxisId}已到位");
                                stepnum = 2;
                            }
                            break;
                        case 2:
                            if (sw.Elapsed.TotalSeconds > 0.5)
                            {
                                sw.Stop();
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {

            }
        }

        public override string Description => "轴Jog运动模块：用于控制指定轴以指定速度、方向和距离进行点动（Jog）运动。";
    }
}